//
//  BaseRequest.m
//  SleepingElf
//
//  Created by karong on 2023/6/7.
//

#import "BaseRequest.h"
#import "GTMBase64.h"
#import "NSData+AES.h"
#import "AFNetworking.h"
#import "MiniLoginPop.h"

@implementation BaseRequest
+ (void)getWithURLString:(NSString *)URLString
              parameters:(id)parameters
                 success:(void (^)(NSDictionary *dataDict))success
                 failure:(Failure)failure
{
    parameters = [self fullParameters:parameters url:URLString];
    [self requestWithMethod:@"GET"
                 URLString:FULL_ADDRESS(URLString)
                parameters:parameters
                   success:success
                   failure:failure];
}

+ (void)postWithURLString:(nonnull NSString *)URLString parameters:(nonnull id)parameters success:(nonnull void (^)(NSDictionary * _Nonnull __strong))success failure:(nonnull Failure)failure {
    
    parameters = [self fullParameters:parameters url:URLString];
    [self requestWithMethod:@"POST"
                  URLString:FULL_ADDRESS(URLString)
                 parameters:parameters
                    success:success
                    failure:failure];
}

+ (void)requestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(id)parameters success:(DictionaryBlock)success failure:(Failure)failure {
    AFHTTPSessionManager *manager = [self defaultAFSessionManager];
    NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:method
                                                                      URLString:URLString
                                                                     parameters:parameters
                                                                          error:nil];
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
        NSDictionary *responseValue = (NSDictionary *)responseObject;
        if (![responseObject isKindOfClass:[NSDictionary class]]){
            NSString * responseContent =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSData *jsonData = [responseContent dataUsingEncoding:NSUTF8StringEncoding];
            responseValue = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        }
        if (responseValue) {
            NSInteger resultCode = [responseValue[@"code"] integerValue];
            if (resultCode == 200) {
                if (success) {
                    success(responseValue);
                }
            }
            else {
                error = error ? error : [NSError errorWithDomain:responseValue[@"msg"] ?: @"" code:resultCode ?: urlResponse.statusCode userInfo:nil];
                if (failure) {
                    failure(urlResponse, error, responseValue);
                }
                [self requestFailureWithURLString:URLString parameters:parameters statusCode:urlResponse.statusCode responseObject:responseObject resultCode:resultCode error:error log:YES];
            }
        }
        else {
            if (responseObject && !error) {
                error = [NSError errorWithDomain:@"Network error. Please try again later" code:NSURLErrorCannotDecodeContentData userInfo:nil];
            }
            if (failure) {
                failure(urlResponse, error, responseObject);
            }
            [self requestFailureWithURLString:URLString parameters:parameters statusCode:urlResponse.statusCode responseObject:responseObject resultCode:0 error:error log:YES];
        }
    }];
    [dataTask resume];
}

+ (void)postWithURLString:(NSString *)URLString
               parameters:(id)parameters
                fileDatas:(NSArray<NSData *> *)fileDatas
                fileNames:(NSArray<NSString *> *)fileNames
                  success:(DictionaryBlock)success
                  failure:(Failure)failure
{
    parameters = [self fullParameters:parameters url:URLString];
    [self postWithURLString:FULL_ADDRESS(URLString) parameters:parameters names:fileNames fileDatas:fileDatas fileNames:fileNames success:success failure:failure];
}


/// 图片上传
+ (void)postWithURLString:(NSString *)URLString
               parameters:(id)parameters
                    names:(NSArray<NSString *> *)names
                fileDatas:(NSArray<NSData *> *)fileDatas
                fileNames:(NSArray<NSString *> *)fileNames
                  success:(DictionaryBlock)success
                  failure:(Failure)failure {
    [AFHTTPSessionManager manager].requestSerializer.timeoutInterval = 60;
    [[AFHTTPSessionManager manager] POST:URLString parameters:parameters headers:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i = 0; i < fileDatas.count; i ++) {
            [formData appendPartWithFileData:fileDatas[i] name:@"file" fileName:fileNames[i] mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *responseValue = (NSDictionary *)responseObject;
        if (![responseObject isKindOfClass:[NSDictionary class]]){
            NSString * responseContent =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSData *jsonData = [responseContent dataUsingEncoding:NSUTF8StringEncoding];
            responseValue = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        }
        NSInteger resultCode = [responseValue[@"code"] integerValue];
        if (responseValue) {
            if (resultCode == 200) {
                if (success) {
                    success(responseValue);
                }
            }
        }
        else if (resultCode == 401 || resultCode == 403){
            //responseValue[@"msg"]
        }else{
            //responseValue[@"msg"] 接口异常
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    return;
}

+ (void)requestFailureWithURLString:(NSString *)URLString parameters:(id)parameters statusCode:(NSInteger)statusCode responseObject:(id)responseObject resultCode:(NSInteger)resultCode error:(NSError *)error log:(BOOL)log {
    if (resultCode == 400 && [error.domain containsString:WSLocalized(@"登录")]) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"LoginController" bundle:nil];
        MiniLoginPop * target = [storyBoard instantiateViewControllerWithIdentifier:@"MiniLoginPop"];
        [[UIViewController currentViewController] presentViewController:target animated:YES completion:nil];
    }
    else {
        [SEToast simple:error.domain];
    }
}
#pragma mark - 頭部信息
+ (NSDictionary *)fullParameters:(NSDictionary*)parameters url:(NSString *)urlString{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    dict[@"app_id"] = @"97806519";
//    dict[@"version"] = [HBTool getVersionCode];
//    dict[@"version_code"] = [HBTool getVersionCode];
//    NSString *language = NSBundle.mainBundle.preferredLocalizations.firstObject;
//    ///zh開頭  顯示繁體
//    if ([language hasPrefix:@"zh"]) {
    NSArray * array = @[@"zh-tw", @"en-us"];
    dict[@"lang"] = array[appConfig.languageType];
    dict[@"os_type"] = @"ios";
//    }
    dict[@"package"] = [[NSBundle mainBundle] infoDictionary][@"CFBundleIdentifier"];
    if (!SEIsNullOrEmpty(appUserCenter.token)) {
        dict[@"token"] = SEEmptyStr(appUserCenter.token);
    }
    dict[@"app_name"] = [[NSBundle mainBundle] infoDictionary][@"CFBundleDisplayName"];
    dict[@"timestamp"] = SESF(@"%ld", (long)[[NSDate date]timeIntervalSince1970]);
    dict[@"Access-Token"] = @"FLkRudvSBjFaTdCqxZeJVzfIsGxAfihG";
    [dict addEntriesFromDictionary:parameters];
    //加密
    NSString * sign = [self sortSys_key:dict];
    sign = [sign stringByAppendingString:@"c9937646-3d3b-60fc-a563-9d27d49d9a64"];
    dict[@"sign"] = [sign md5String];
    return dict;
}

+ (AFHTTPSessionManager *)defaultAFSessionManager {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 13.f;
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", @"text/html", nil];
    return manager;
}

#pragma mark----按照升序排列-----
+ (NSString *)sortSys_key:(NSDictionary *)sys_keyDic{
    NSArray *allKeys = [sys_keyDic allKeys];
    NSArray *sortAllKeys = [allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSOrderedAscending];
    }];
    
    NSMutableString * sys_keySorted = [NSMutableString new];
    for (NSString * key in sortAllKeys) {
        if (sys_keySorted.length > 0) {
            [sys_keySorted appendString:@"&"];
        }
        [sys_keySorted appendString:SESF(@"%@=%@",key,sys_keyDic[key])];
    }
    return sys_keySorted;
}

@end
